package com.solocredit.finance.data.analyse.util

import android.app.Application
import android.os.Build
import android.os.Handler
import android.os.Looper
import com.google.android.gms.tasks.Task
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.analytics
import com.google.firebase.analytics.ktx.logEvent
import com.google.firebase.ktx.Firebase
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.data.analyse.AnalyseBuilder
import com.solocredit.finance.data.analyse.AnalyseUtil
import com.solocredit.finance.data.analyse.type.IAnalyseEvent
import com.solocredit.finance.http.ApiService.addCommonParams
import org.json.JSONObject
import java.util.Locale


/**
 * Firebase
 */
object FirebaseUtil {

    /** 句柄 */
    private var mFirebaseAnalytics: FirebaseAnalytics = Firebase.analytics

    /** firebase app id, 服务端回推firebase事件使用 */
    private var mFirebaseAppId: String = ""

    /** ga4 instance id, 服务端回推firebase事件使用 */
    private var mGa4InstanceId: String = ""

    /**
     * 初始化
     *
     * @param context Application
     */
    fun init(context: Application,success: (String,String) -> Unit) {
        try {
            if (mFirebaseAppId.isBlank()) {
                Thread {
                    if (Looper.getMainLooper() != Looper.myLooper()) {
                        mFirebaseAppId = FirebaseAnalytics.getInstance(context).firebaseInstanceId
                        MullaLog.i("mFirebaseAppId=$mFirebaseAppId")

                        if (mFirebaseAppId.isNotBlank()){
                            Handler(Looper.getMainLooper()).post {
                                //回调通知
                                success.invoke(getFirebaseAppId(), getGa4InstanceId())
                            }
                        }
                    } else {
                        MullaLog.i("init Firebase ERROR! Cannot call in the main thread, You must call in the other thread")
                    }
                }.start()
            } else {
                Handler(Looper.getMainLooper()).post {
                    //回调通知
                    success.invoke(getFirebaseAppId(), getGa4InstanceId())
                }
            }

            if (mGa4InstanceId.isBlank()) {
                val gResult: Task<String?> = FirebaseAnalytics.getInstance(context).appInstanceId
                gResult.addOnSuccessListener {
                    mGa4InstanceId = it?:""
                    MullaLog.i("mGa4InstanceId=$mGa4InstanceId")

                    if (mGa4InstanceId.isNotBlank()){
                        Handler(Looper.getMainLooper()).post {
                            //回调通知
                            success.invoke(getFirebaseAppId(), getGa4InstanceId())
                        }
                    }
                }
            } else {
                //回调通知
                success.invoke(getFirebaseAppId(), getGa4InstanceId())
            }
        } catch (e: Exception) {
              MullaLog.e(e.message)
        }
    }

    /**
     * 打点
     *
     * @param event 事件名
     */
    fun addEvent(event: IAnalyseEvent) {
        try {
            when (event) {
                IAnalyseEvent.AT_REGISTER -> {
                    mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SIGN_UP) {
                        param(FirebaseAnalytics.Param.METHOD, IAnalyseEvent.AT_REGISTER.name)
                    }
                }
                IAnalyseEvent.AT_LOAN_APPLY -> {
                    mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.PURCHASE) {
                        param(
                            FirebaseAnalytics.Param.CONTENT_TYPE,
                            IAnalyseEvent.AT_LOAN_APPLY.name
                        )
                        param(
                            FirebaseAnalytics.Param.AFFILIATION,
                            IAnalyseEvent.AT_LOAN_APPLY.name
                        )
                        param(FirebaseAnalytics.Param.COUPON, IAnalyseEvent.AT_LOAN_APPLY.name)
                        param(
                            FirebaseAnalytics.Param.TRANSACTION_ID,
                            IAnalyseEvent.AT_LOAN_APPLY.name
                        )
                        param(FirebaseAnalytics.Param.VALUE, "1")
                        param(FirebaseAnalytics.Param.SHIPPING, "1")
                        param(FirebaseAnalytics.Param.TAX, "1")
                        param(FirebaseAnalytics.Param.CURRENCY, "USD")
                    }
                }
            }
        } catch (e: Exception) {
                MullaLog.e(e.message)
        }
    }

    /**
     * 保存 firebase s2s 信息
     */
    fun saveS2SInfo() {
        val params = JSONObject().addCommonParams().apply {
//            put("path", "{接口映射}")
            put("name", AnalyseBuilder.appPckName)
            put("OSAndVersion", "Android ${Build.VERSION.RELEASE}")
            put("locale", Locale.getDefault().toString())
            put("device", Build.MODEL.toString())
            put("appVersion", AnalyseBuilder.appVersion)
            put("sdkVersion", Build.VERSION.SDK_INT.toString())
            put("device", "Build/${Build.ID}")
            put("lat", AnalyseUtil.getAdEnabled().toString())
            put("firebaseAppId", getFirebaseAppId())
            put("ga4AppInstanceId", getGa4InstanceId())
        }

//        val body: String = AesUtil.encryptDefault(params.toString())
        val body: String = params.toString()
        val path = AnalyseBuilder.pathFirebaseInstall
        val url = UrlHelper.combineUrl(path)
        AnalysisHttpHelper.doPostAction(url,body)
    }

    /**
     * 获取Firebase App Id
     */
    private fun getFirebaseAppId(): String {
        return mFirebaseAppId
    }

    /**
     * 获取Firebase Ga4 instance Id
     */
    private fun getGa4InstanceId(): String {
        return mGa4InstanceId
    }
}